package service.msm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import service.edu.result.R;
import service.msm.service.MsmService;
import service.edu.utils.RandomUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("/msm")
@RestController
@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信
    @GetMapping("send/{phoneNum}")
    public R sendMsm(@PathVariable("phoneNum")String phoneNum){
        String code = redisTemplate.opsForValue().get(phoneNum);
        //判断redis中是否有相应手机号
        if (!StringUtils.isEmpty(code)){return R.Ok();}

        //利用随机生成数工具类获得随机数作为验证码
        code = RandomUtil.getFourBitRandom();//4位随机数
        //将随机数传递给阿里云并由之发送
        Map<String,Object> param=new HashMap<>();
        param.put("verificationCode", code);
        //调用service方法实现发送
        boolean isSend= msmService.send(param,phoneNum);
        if (isSend){
            //将验证码存入redis并只保存5分钟
            redisTemplate.opsForValue().set(phoneNum, code,5, TimeUnit.MINUTES);
            return R.Ok();
        }else {
            return R.Error().message("短信发送失败");
        }
    }
}
